package com.hanbang.chu_xing_gao_zhao.view_find_classroom;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.application.MyApplication;
import com.hanbang.chu_xing_gao_zhao.base.BaseActivity;
import com.hanbang.chu_xing_gao_zhao.entity.PopupData;
import com.hanbang.chu_xing_gao_zhao.myview.CalendarPickerUtil;
import com.hanbang.chu_xing_gao_zhao.myview.GridViewForScrollView;
import com.hanbang.chu_xing_gao_zhao.myview.MorePopupWindowPublic;
import com.hanbang.chu_xing_gao_zhao.myview.MyDialog;
import com.hanbang.chu_xing_gao_zhao.utils.MyLog;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MySharedPreferences;
import com.hanbang.chu_xing_gao_zhao.utils.MyToast;
import com.hanbang.chu_xing_gao_zhao.utils.StringUtils_2;
import com.hanbang.chu_xing_gao_zhao.utils.SystemTools;
import com.hanbang.chu_xing_gao_zhao.utils.UiUtils;
import com.hanbang.cxgz_2.R;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 课堂的申请
 */
public class FindClassroomApplyActivity extends BaseActivity {
    /**
     * 显示图片
     */
    private ImageView showPicture;
    /**
     * 添加图片
     */
    private LinearLayout addPicture;
    /**
     * 名字
     */
    private TextView name;
    /**
     * 选择模试
     */
    private LinearLayout selectModel;
    /**
     * 课堂名称
     */
    private EditText classroomName;
    /**
     * 课堂简介
     */
    private EditText classroomBrief;
    /**
     * 开始年
     */
    private TextView beginYear;
    /**
     * 开始月
     */
    private TextView beginMonth;
    /**
     * 开始日
     */
    private TextView beginDay;
    /**
     * 时
     */
    private TextView hour;
    /**
     * 分
     */
    private TextView minute;
    /**
     * 秒
     */
    private TextView second;
    /**
     * 授课地点
     */
    private EditText location;
    /**
     * 免费
     */
    private TextView free;
    /**
     * 收费
     */
    private TextView charge;
    /**
     * 价格
     */
    private EditText price;
    /**
     * 上传
     */
    private TextView uploading;
    /**
     * 选择时间
     */
    private LinearLayout selectCalendar;

    /**
     * 时间-小时
     */
    private ArrayList<PopupData> hourList = new ArrayList<PopupData>();
    /**
     * 时间-分钟
     */
    private ArrayList<PopupData> minuteList = new ArrayList<PopupData>();
    /**
     * 时间-秒
     */
    private ArrayList<PopupData> secondlist = new ArrayList<PopupData>();
    /**
     * 选择模试-线下
     */
    private CheckBox offlineClassroom;
    /**
     * 选择模试-视频
     */
    private CheckBox videoClassroom;
    /**
     * 选择模试-id
     * 线下或视频
     * 课堂形式，1为线下课堂，2为视频课堂
     */
    private int modelLine = 1;
    /**
     * 费用模试
     * 免费的为0
     */
    private int modelCost = 0;
    /**
     * 图片路径
     */
    private String pathPicture = "";

    /**
     * 图片视频路径
     */
    private String path = "";
    /**
     * 图片路径
     */
    private ArrayList<String> picturePathData;
    /**
     * 图片显示
     */
    private GridViewForScrollView pictureShowGridview;
    /**
     * 图片适配器
     */
    private PictureShowAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.find_classroom_apply);
        initView();
        setOnClickListener();

    }

    /**
     * 初始化view
     */
    private void initView() {
        setTitleMore(View.VISIBLE, View.INVISIBLE, "申请开课", null, null, null);
        setBackArrows(findViewById(R.id.bar_top_conver_classify_back));

        showPicture = (ImageView) findViewById(R.id.iv_find_classroom_apply_showPicture);
        addPicture = (LinearLayout) findViewById(R.id.ll_find_classroom_apply_addPicture);
        name = (TextView) findViewById(R.id.tv_find_classroom_apply_name);
        selectModel = (LinearLayout) findViewById(R.id.ll_find_classroom_apply_selectModel);
        classroomName = (EditText) findViewById(R.id.et_find_classroom_apply_classroomName);
        classroomBrief = (EditText) findViewById(R.id.et_find_classroom_apply_classroomBrief);
        beginYear = (TextView) findViewById(R.id.et_find_classroom_apply_beginYear);
        beginMonth = (TextView) findViewById(R.id.et_find_classroom_apply_beginMonth);
        beginDay = (TextView) findViewById(R.id.et_find_classroom_apply_beginDay);
        hour = (TextView) findViewById(R.id.et_find_classroom_apply_hour);
        minute = (TextView) findViewById(R.id.et_find_classroom_apply_minute);
        second = (TextView) findViewById(R.id.et_find_classroom_apply_second);
        location = (EditText) findViewById(R.id.et_find_classroom_apply_location);
        free = (TextView) findViewById(R.id.tv_find_classroom_apply_free);
        charge = (TextView) findViewById(R.id.tv_find_classroom_apply_charge);
        price = (EditText) findViewById(R.id.et_find_classroom_apply_price);
        uploading = (TextView) findViewById(R.id.tv_find_classroom_apply_uploading);
        selectCalendar = (LinearLayout) findViewById(R.id.ll_find_classroom_apply_selectCalendar);
        offlineClassroom = (CheckBox) findViewById(R.id.cb_find_classroom_apply_offline);
        videoClassroom = (CheckBox) findViewById(R.id.cb_find_classroom_apply_video);


        name.setText(userData.getUser_name());

        //默认为线下模式
        offlineClassroom.setSelected(true);
        modelLine = 1;

        //添加图片与视频初始化
        pictureShowGridview = (GridViewForScrollView) findViewById(R.id.gv_find_classroom_apply_pictureShow);
        picturePathData = new ArrayList<String>();
        adapter = new PictureShowAdapter(picturePathData);
        pictureShowGridview.setAdapter(adapter);


    }

    /**
     * 设置点击事件
     */
    private void setOnClickListener() {
        selectCalendar.setOnClickListener(onClickListener);
        hour.setOnClickListener(onClickListener);
        minute.setOnClickListener(onClickListener);
        second.setOnClickListener(onClickListener);
        free.setOnClickListener(onClickListener);
        charge.setOnClickListener(onClickListener);
        showPicture.setOnClickListener(onClickListener);
        uploading.setOnClickListener(onClickListener);

    }


    private String initEndDateTime = "2014年8月23日 17:44"; // 初始化结束时间
    /**
     * 处理监听
     */
    @SuppressWarnings("unused")
    private OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            MorePopupWindowPublic popup = null;

            switch (v.getId()) {
                //选择日期
                case R.id.ll_find_classroom_apply_selectCalendar:
                    CalendarPickerUtil dateTimePicKDialog = new CalendarPickerUtil(FindClassroomApplyActivity.this, 100);
                    dateTimePicKDialog.dateTimePicKDialog();

                    dateTimePicKDialog.setOnClickCallback(new CalendarPickerUtil.OnClickCallback() {
                        @Override
                        public void onclick(String content) {
                            beginYear.setText(StringUtils_2.getString(content, 0, "年"));
                            beginMonth.setText(StringUtils_2.getString(content, "年", "月"));
                            beginDay.setText(StringUtils_2.getString(content, "月", "日"));
                        }
                    });

                    break;
                //选择小时
                case R.id.et_find_classroom_apply_hour:
                    addData(hourList, 24);
                    popup = new MorePopupWindowPublic(FindClassroomApplyActivity.this, R.layout.item_popupwindow_public, hourList, 8);
                    popup.showPopupWindow(hour, 2);
                    break;
                //选择分
                case R.id.et_find_classroom_apply_minute:
                    addData(minuteList, 60);
                    popup = new MorePopupWindowPublic(FindClassroomApplyActivity.this, R.layout.item_popupwindow_public, minuteList, 8);
                    popup.showPopupWindow(minute, 2);
                    break;
                //选择秒
                case R.id.et_find_classroom_apply_second:
                    addData(secondlist, 60);
                    popup = new MorePopupWindowPublic(FindClassroomApplyActivity.this, R.layout.item_popupwindow_public, secondlist, 8);
                    popup.showPopupWindow(second, 2);
                    break;
                //选择免费
                case R.id.tv_find_classroom_apply_free:
                    modelCost = 0;
                    free.setBackgroundResource(R.drawable.bg_corners12__yellow_background);
                    charge.setBackgroundResource(R.drawable.bg_corners12_graydd_background);
                    price.setFocusable(false);
                    price.setFocusableInTouchMode(false);
                    price.setText("");
                    break;
                //选择收费
                case R.id.tv_find_classroom_apply_charge:
                    modelCost = 1;
                    free.setBackgroundResource(R.drawable.bg_corners12_graydd_background);
                    charge.setBackgroundResource(R.drawable.bg_corners12__yellow_background);
                    price.setFocusable(true);
                    price.setFocusableInTouchMode(true);
                    break;
                case R.id.tv_find_classroom_apply_uploading:
                    if (pathPicture.equals("")) {
                        MyToast.show(FindClassroomApplyActivity.this, "标题图片不能为空", Toast.LENGTH_SHORT);
                        return;
                    }
                    if (name.getText().toString().equals("")) {
                        MyToast.show(FindClassroomApplyActivity.this, "标题不能为空", Toast.LENGTH_SHORT);
                        return;
                    }

                    if (classroomBrief.getText().toString().equals("")) {
                        MyToast.show(FindClassroomApplyActivity.this, "课堂简介不能为空", Toast.LENGTH_SHORT);
                        return;
                    }

                    if (beginYear.getText().toString().equals("")) {
                        MyToast.show(FindClassroomApplyActivity.this, "授课日期不能为空", Toast.LENGTH_SHORT);
                        return;
                    }

                    if (hour.getText().toString().equals("") || minute.getText().toString().equals("") || second.getText().toString().equals("")) {
                        MyToast.show(FindClassroomApplyActivity.this, "授课时间不能为空", Toast.LENGTH_SHORT);
                        return;
                    }

                    if (location.getText().toString().equals("")) {
                        MyToast.show(FindClassroomApplyActivity.this, "授课地点不能为空", Toast.LENGTH_SHORT);
                        return;
                    }

                    if (picturePathData.size() == 0) {
                        MyToast.show(FindClassroomApplyActivity.this, "课堂图片与视频不能为空", Toast.LENGTH_SHORT);
                        return;
                    }
                    if (modelCost == 1 && price.getText().toString().equals("")) {
                        MyToast.show(FindClassroomApplyActivity.this, "收费模式价格不能为空", Toast.LENGTH_SHORT);
                        return;
                    }


                    httpClassroomApply();
                    break;


                //选择相片
                case R.id.iv_find_classroom_apply_showPicture:
                    // 新建一个dialog 对话框
                    MyDialog myDialog = new MyDialog(FindClassroomApplyActivity.this, R.style.about_me_dialog, MyDialog.MODE.HEAD);
                    // 添加图片的监听
                    myDialog.setOnClickCallback(new com.hanbang.chu_xing_gao_zhao.myview.MyDialog.OnClickCallback() {

                        @Override
                        public void onClick(MyDialog dialog, Object number, Object content) {

                            // 拍照
                            if ((Integer) number == 1) {
                                pathPicture = "";
                                File fDir = new File(MyApplication.picFilepath);
                                pathPicture = System.currentTimeMillis() + ".jpg";
                                if (fDir.exists() || fDir.mkdirs()) {
                                    File cameraFile = new File(fDir, pathPicture);
                                    if (!cameraFile.exists()) {
                                        try {
                                            cameraFile.createNewFile();
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
                                    startActivityForResult(intent, 887);
                                }
                                // 相册选择
                            } else if ((Integer) number == 2) {
                                // 获取相册
                                Intent intent = new Intent();
                                intent.setType("image/*");

                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                intent.putExtra("return-data", true);
                                startActivityForResult(intent, 888);
                            }

                        }
                    });
                    myDialog.show();

                    break;

                default:
                    break;


            }

            //选择时间的回调
            if (popup != null) {
                popup.setOnClickCallback(new MorePopupWindowPublic.OnClickCallback() {
                    @Override
                    public void onClick(MorePopupWindowPublic morePopWindow, Object number, String content) {
                        for (int i = 0; i < morePopWindow.parentView.size(); i++) {
                            if ((Integer) number == i) {

                                if (morePopWindow.view.getId() == R.id.et_find_classroom_apply_hour) {
                                    hour.setText(content);
                                }
                                if (morePopWindow.view.getId() == R.id.et_find_classroom_apply_minute) {
                                    minute.setText(content);
                                }
                                if (morePopWindow.view.getId() == R.id.et_find_classroom_apply_second) {
                                    second.setText(content);
                                }

                                Toast.makeText(FindClassroomApplyActivity.this, content, Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                });
            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 获取图片地址
         */
        if (requestCode == 888 && resultCode == -1) {
            Uri uri = data.getData();
            pathPicture = SystemTools.getPath(FindClassroomApplyActivity.this, uri);
            bitmapUtils.display(showPicture, pathPicture);
            addPicture.setVisibility(View.GONE);
            // 获取拍照的图片路径
        } else if (requestCode == 887 && resultCode == -1) {
            File fDir = new File(MyApplication.picFilepath);
            // 判断文件夹是否存在
            if (fDir.exists() || fDir.mkdirs()) {
                File cameraFile = new File(fDir, pathPicture);
                // 判断文件时是否存在
                if (cameraFile.exists()) {
                    pathPicture = cameraFile.getPath();
                    bitmapUtils.display(showPicture, pathPicture);
                    addPicture.setVisibility(View.GONE);
                } else {
                    MyToast.show(FindClassroomApplyActivity.this, "获取照片失败！", Toast.LENGTH_SHORT);
                }
            } else {
                MyToast.show(FindClassroomApplyActivity.this, "获取照片失败！", Toast.LENGTH_SHORT);
            }
        }


        /**
         * 获取图片与视频地址
         */
        if (requestCode == 999 && resultCode == -1) {
            Uri uri = data.getData();
            path = SystemTools.getPath(FindClassroomApplyActivity.this, uri);
            picturePathData.add(path);
            adapter.notifyDataSetChanged();
            MyLog.i("text", "*111**" + path);// *****

            // 获取拍照的图片路径
        } else if (requestCode == 998 && resultCode == -1) {
            File fDir = new File(MyApplication.picFilepath);
            // 判断文件夹是否存在
            if (fDir.exists() || fDir.mkdirs()) {
                File cameraFile = new File(fDir, path);
                // 判断文件时是否存在
                if (cameraFile.exists()) {
                    path = cameraFile.getPath();

                    picturePathData.add(path);
                    adapter.notifyDataSetChanged();
                    MyLog.i("text", "*222**" + cameraFile.getPath());// *****

                } else {
                    MyToast.show(FindClassroomApplyActivity.this, "获取照片失败！", Toast.LENGTH_SHORT);
                }
            } else {
                MyToast.show(FindClassroomApplyActivity.this, "获取照片失败！", Toast.LENGTH_SHORT);
            }
        }

    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }


    /**
     * 选择模式
     */
    public void checkBoxListener(View v) {
        CheckBox ll = (CheckBox) v;
        if (v.getId() == offlineClassroom.getId()) {
            offlineClassroom.setSelected(true);
            videoClassroom.setSelected(false);
            modelLine = 1;

        } else if (v.getId() == videoClassroom.getId()) {
            offlineClassroom.setSelected(false);
            videoClassroom.setSelected(true);
            modelLine = 2;
        }
    }


    /**
     * 为时，分，秒 ，添加数据
     */
    private void addData(ArrayList<PopupData> list, int maxNum) {

        if (list.size() != 0) {
            return;
        }
        PopupData data;
        for (int i = 1; i <= maxNum; i++) {
            if (i < 10) {
                data = new PopupData(0, "0" + i, 0, null);
            } else {

                data = new PopupData(0, i + "", 0, null);
            }
            list.add(data);

        }
    }

    /**
     * gridview adapter
     *
     * @author Administrator
     */
    class PictureShowAdapter extends BaseAdapter {
        public ArrayList<String> list;

        public PictureShowAdapter(ArrayList<String> list) {

            if (list != null) {
                this.list = list;

            } else {
                list = new ArrayList<String>();

            }
        }

        @Override
        public int getCount() {
            return list.size() + 1;
        }

        @Override
        public String getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            UiUtils.applyFont(convertView);
            ViewHolder viewHolder;
            if (convertView == null) {// 是空加载
                convertView = getLayoutInflater().inflate(R.layout.item_dycamic_horizontal_listview_delect, null);
                viewHolder = new ViewHolder();
                viewHolder.picture = (ImageView) convertView.findViewById(R.id.iv_item_shoppingcart_recommend_image);
                viewHolder.deletePicture = (ImageView) convertView
                        .findViewById(R.id.iv_item_shoppingcart_recommend_delete);
                convertView.setTag(viewHolder);
            } else {// 不是空复用

                viewHolder = (ViewHolder) convertView.getTag();
            }

            // 添加加号
            if (position == list.size()) {
                viewHolder.picture.setPadding(10, 70, +70 + 60, 70);
                viewHolder.picture.setImageResource(R.drawable.add);
                viewHolder.deletePicture.setVisibility(View.GONE);
                // 添加图片
            } else {
                viewHolder.picture.setPadding(0, 0, 0, 00);
                viewHolder.deletePicture.setVisibility(View.VISIBLE);
                //如果是视频则显示一个播放按钮
                if (StringUtils_2.getText(list.get(position), ".").equals("mp4")) {
                    viewHolder.picture.setImageResource(R.drawable.play);

                } else {
                    bitmapUtils.display(viewHolder.picture, list.get(position));
                }


            }

            viewHolder.picture.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {


                    // 新建一个dialog 对话框
                    MyDialog myDialog = new MyDialog(FindClassroomApplyActivity.this, R.style.about_me_dialog, MyDialog.MODE.HEAD);
                    // 添加图片的监听
                    myDialog.setOnClickCallback(new com.hanbang.chu_xing_gao_zhao.myview.MyDialog.OnClickCallback() {

                        @Override
                        public void onClick(MyDialog dialog, Object number, Object content) {

                            // 拍照
                            if ((Integer) number == 1) {
                                File fDir = new File(MyApplication.picFilepath);
                                path = System.currentTimeMillis() + ".jpg";
                                if (fDir.exists() || fDir.mkdirs()) {
                                    File cameraFile = new File(fDir, path);
                                    if (!cameraFile.exists()) {
                                        try {
                                            cameraFile.createNewFile();
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
                                    startActivityForResult(intent, 998);
                                }
                                // 相册选择
                            } else if ((Integer) number == 2) {
                                // 获取相册
                                Intent intent = new Intent();
                                intent.setType("image/*;video/*");
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                intent.putExtra("return-data", true);
                                startActivityForResult(intent, 999);
                            }

                        }
                    });
                    myDialog.show();
                }
            });

            // 删除图片
            viewHolder.deletePicture.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    picturePathData.remove(position);
                    adapter.notifyDataSetChanged();

                }
            });

            return convertView;
        }

        class ViewHolder {// 进行缓存保存
            private ImageView picture; // 图片
            private ImageView deletePicture; // 删除 图片

        }

    }

    /**
     * 申请课堂
     * address：开课地址
     * begin_time：开课时间，格式为yyyy-MM-dd HH:mm:ss
     * price:价格，免费的为0
     * remark：课堂简介
     * title：标题
     * type：课堂形式，1为线下课堂，2为视频课堂
     * img_url：组图片，只有一张
     * img_guocheng：视频/图片正文，可多个一起传
     */
    private void httpClassroomApply() {

        RequestParams params = new RequestParams();
        params.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                FindClassroomApplyActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
        params.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                FindClassroomApplyActivity.this, MySharedPreferences.USER_DATA, "password"));

        params.addBodyParameter("address", location.getText().toString());
        params.addBodyParameter("begin_time", beginYear.getText().toString() + "-"
                + beginMonth.getText().toString() + "-"
                + beginDay.getText().toString() + " "
                + hour.getText().toString() + ":"
                + minute.getText().toString() + ":"
                + second.getText().toString());
        params.addBodyParameter("price", price.getText().toString());
        params.addBodyParameter("remark", classroomBrief.getText().toString());
        params.addBodyParameter("title", name.getText().toString());
        params.addBodyParameter("type", modelLine + "");

        //主图片``
        File f = new File(pathPicture);
        params.addBodyParameter("img_url", f);


        //多个图片与视频
        for (int i = 0; i < picturePathData.size(); i++) {

            File picture = new File(picturePathData.get(i));

            if (picture.exists()) {

                params.addBodyParameter("img_guocheng", picture);

                MyLog.i("text", picture.getPath() + "");
            }
        }


        httpUtils.send(HttpRequest.HttpMethod.POST, HttpInterfaces.ketang_Add, params,
                new MyRequestCallBack<String>(this, "正在申请上传...") {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        super.onSuccess(responseInfo);

                        try {
                            JSONObject json = new JSONObject(responseInfo.result);
                            int statrs = json.getInt("Result");
                            String msg = json.getString("Msg");
                            if (statrs == 0) {
                                MyToast.show(FindClassroomApplyActivity.this, "申请成功", Toast.LENGTH_LONG);
                                finish();
                            } else {
                                MyToast.show(FindClassroomApplyActivity.this, msg, Toast.LENGTH_LONG);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            MyToast.show(FindClassroomApplyActivity.this, "服务器忙请稍后重试...", Toast.LENGTH_LONG);
                        }
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        super.onLoading(total, current, isUploading);


                    }
                });

    }

}
